import React, { useState, useEffect } from 'react';
import { Table, Select, DatePicker, Button, Space, Empty, Modal, Input, Radio, message } from 'antd';
import styles from './MemberManagement.module.css';
import { _apiMemberList, _apiMemberInfo ,_apiMemberRecharge,_apiPayType,_apiRechargeList,_apiIntegralList,_apiOrderList,_apiCouponList} from '../../../api';

const { RangePicker } = DatePicker;
const { Option } = Select;

const MemberManagement = () => {
  // 状态管理
  const [selectedStore, setSelectedStore] = useState('1');
  const [selectedOrders, setSelectedOrders] = useState('1');
  const [showDetail, setShowDetail] = useState(false);
  const [currentMember, setCurrentMember] = useState(null);
  const [activeTab, setActiveTab] = useState('storage');
  const [isPointsModalVisible, setIsPointsModalVisible] = useState(false);
  const [pointsForm, setPointsForm] = useState({
    currentPoints: '',
    changeAmount: '',
    remark: ''
  });
  const [isRechargeModalVisible, setIsRechargeModalVisible] = useState(false);
  const [rechargeForm, setRechargeForm] = useState({
    rechargeAmount: '',
    paymentMethod: '' // 初始为空，等待接口数据
  });
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [editForm, setEditForm] = useState({
    name: '',
    phone: '',
    gender: '男'
  });
  const [loading, setLoading] = useState(false);
  const [memberList, setMemberList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [paymentTypes, setPaymentTypes] = useState([]);
  const [rechargeRecords, setRechargeRecords] = useState([]);
  const [rechargeLoading, setRechargeLoading] = useState(false);
  const [integralRecords, setIntegralRecords] = useState([]);
  const [integralLoading, setIntegralLoading] = useState(false);
  const [couponRecords, setCouponRecords] = useState([]);
  const [couponLoading, setCouponLoading] = useState(false);
  const [orderData, setOrderData] = useState([]);
  const [orderLoading, setOrderLoading] = useState(false);
  
  // 表格列定义
  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 80,
      render: (_, record, index) => index + 1,
    },
    {
      title: '会员信息',
      key: 'memberInfo',
      
      render: (_, record) => (
        <div className={styles.memberInfo}>
          <img src={record.avatar || ''} alt="avatar" className={styles.avatar} />
          <div>
            <div>{record.realName || record.userName || ''}</div>
            <div>{record.phone || ''}</div>
          </div>
        </div>
      ),
    },
    {
      title: '积分',
      dataIndex: 'point',
      key: 'point',
      render: (point) => point || 0,
    },
    {
      title: '下单次数',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      render: (orderAmount) => orderAmount || 0,
    },
    {
      title: '下单金额',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      render: (orderAmount) => Number(orderAmount || 0).toFixed(2),
    },
    {
      title: '是否为付费会员',
      dataIndex: 'groupTitle',
      key: 'groupTitle',
      render: (groupTitle) => groupTitle || '-',
    },
    {
      title: '卡内余额',
      dataIndex: 'amount',
      key: 'balance',
      render: (amount) => Number(amount || 0).toFixed(2),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a className={styles.link} onClick={async () => {
            try {
              const response = await _apiMemberInfo({
                userId: record.userId
              });
              console.log('会员详情数据:', response);
              handleMemberDetail(record);
            } catch (error) {
              console.error('获取会员详情失败:', error);
            }
          }}>会员详情</a>
          {/* <a className={styles.link} onClick={() => handlePointsModify(record)}>修改积分</a> */}
          <a className={styles.link} onClick={() => handleRecharge(record)}>充值</a>
        </Space>
      ),
    },
  ];

  // 储值记录表格列定义
  const storageColumns = [
    {
      title: '操作时间',
      dataIndex: 'addTime',
      key: 'addTime',
    },
    {
      title: '操作前余额(元)',
      dataIndex: 'amount',
      key: 'amount',
    },
    {
      title: '充值金额(元)',
      dataIndex: 'rechargeAmount',
      key: 'rechargeAmount',
      render: (text) => <span style={{ color: '#52c41a' }}>+{text}</span>,
    },
    {
      title: '赠送金额(元)',
      dataIndex: 'bonusAmount',
      key: 'bonusAmount',
      render: (text) => <span style={{ color: '#52c41a' }}>+{text}</span>,
    },
    {
      title: '充值后余额(元)',
      dataIndex: 'afterAmount',
      key: 'afterAmount',
      render: (text) => <span style={{ color: '#faad14' }}>{text}</span>,
    },
    {
      title: '操作原因',
      dataIndex: 'reason',
      key: 'reason',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    },
  ];

  // 积分记录表格列定义
  const pointsColumns = [
    {
      title: '操作时间',
      dataIndex: 'addTime',
      key: 'addTime',
    },
    {
      title: '操作前积分',
      dataIndex: 'currPoint',
      key: 'currPoint',
      render: (text) => text || 0,
    },
    {
      title: '积分变值',
      dataIndex: 'value',
      key: 'value',
      render: (text) => (
        <span style={{ color: text > 0 ? '#52c41a' : '#ff4d4f' }}>
          {text > 0 ? `+${text}` : text}
        </span>
      ),
    },
    {
      title: '操作后积分',
      key: 'afterPoints',
      render: (_, record) => {
        const afterPoints = (record.currPoint || 0) + (record.value || 0);
        return afterPoints || 0;
      },
    },
    {
      title: '操作原因',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      render: (text) => text || '无',
    },
  ];

  // 修改优惠券表格列定义
  const couponColumns = [
    {
      title: '操作时间',
      dataIndex: 'addTime',
      key: 'addTime',
    },
    {
      title: '优惠券名称',
      dataIndex: 'merchantTitle',
      key: 'merchantTitle',
    },
    {
      title: '面值(元)',
      dataIndex: 'amount',
      key: 'amount',
      render: (text) => <span style={{ color: '#52c41a' }}>{text}</span>,
    },
    {
      title: '使用状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 0 ? '#52c41a' : '#faad14' }}>
          {status === 0 ? '未使用' : '已使用'}
        </span>
      ),
    },
    {
      title: '操作备注',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '操作',
      key: 'action',
      render: () => (
        <a style={{ color: '#1890ff' }}>删除</a>
      ),
    },
  ];

  // 订单记录表格列定义
  const orderColumns = [
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
    },
      {
        title: '订单金额',
        dataIndex: 'orderAmount',
        key: 'orderAmount',
      },
      {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '创建时间',
      dataIndex: 'addTime',
      key: 'addTime',
    }
  ];

  // 添加积分记录表格列定义
  const integralColumns = [
    {
      title: '操作时间',
      dataIndex: 'addTime',
      key: 'addTime',
      width: 180,
    },
    {
      title: '操作前积分',
      dataIndex: 'currPoint',
      key: 'currPoint',
      width: 120,
    },
    {
      title: '积分变值',
      dataIndex: 'value',
      key: 'value',
      width: 120,
      render: (value) => {
        const isPositive = value > 0;
        return (
          <span style={{ color: isPositive ? '#52c41a' : '#ff4d4f' }}>
            {isPositive ? `+${value}` : value}
          </span>
        );
      }
    },
    {
      title: '操作后积分',
      key: 'afterPoint',
      width: 120,
      render: (_, record) => {
        return record.currPoint + record.value;
      }
    },
    {
      title: '操作原因',
      dataIndex: 'description',
      key: 'description',
      width: 200,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
    }
  ];

  // 格式化日期函数
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  };

 
  


  

  // 空状态组件
  const EmptyState = () => (
    <Empty
      image={Empty.PRESENTED_IMAGE_SIMPLE}
      description="暂无相关记录"
    />
  );

  // 处理修改积分按钮点击
  const handlePointsModify = (record) => {
    setPointsForm({
      currentPoints: record.point || 0,
      changeAmount: '',
      remark: ''
    });
    setIsPointsModalVisible(true);
  };

  // 处理表单输入变化
  const handlePointsFormChange = (field, value) => {
    setPointsForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理提交修改积分
  const handlePointsSubmit = () => {
    // TODO: 处理积分修改提交逻辑
    setIsPointsModalVisible(false);
  };

  // 修改积分弹窗
  const renderPointsModal = () => (
    <Modal
      title="修改积分"
      open={isPointsModalVisible}
      onOk={handlePointsSubmit}
      onCancel={() => setIsPointsModalVisible(false)}
      okText="提交"
      cancelText="取消"
      width={500}
    >
      <div className={styles.formItem}>
        <span className={styles.label}>当前积分：</span>
        <Input 
          value={pointsForm.currentPoints}
          disabled
          style={{ width: '100%' }}
        />
      </div>
      <div className={styles.formItem}>
        <span className={styles.label}>数量：</span>
        <Input
          value={pointsForm.changeAmount}
          onChange={e => handlePointsFormChange('changeAmount', e.target.value)}
          placeholder="请输入积分数值(增加/减少积分+/-值)"
          style={{ width: '100%' }}
        />
      </div>
      <div className={styles.formItem}>
        <span className={styles.label}>备注：</span>
        <Input.TextArea
          value={pointsForm.remark}
          onChange={e => handlePointsFormChange('remark', e.target.value)}
          placeholder="请输入"
          rows={4}
          style={{ width: '100%' }}
        />
      </div>
    </Modal>
  );

  // 处理充值按钮点击
  const handleRecharge = (record) => {
    setCurrentMember(record);
    setRechargeForm({
      rechargeAmount: '',
      paymentMethod: '' // 初始为空，等待接口数据
    });
    setIsRechargeModalVisible(true);
  };

  // 处理充值表单输入变化
  const handleRechargeFormChange = (field, value) => {
    setRechargeForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理提交充值
  const handleRechargeSubmit = async () => {
    try {
      if (!rechargeForm.rechargeAmount || !rechargeForm.paymentMethod) {
        alert('请填写充值金额和选择支付方式');
        return;
      }

      const params = {
        userId: currentMember.userId,
        amount: Number(rechargeForm.rechargeAmount),
        paymentId: Number(rechargeForm.paymentMethod)
      };



      const config = {
        headers: {
          'Content-Type': 'application/json'
        }
      };

      const response = await _apiMemberRecharge(params, config);
      
    

      if (response?.status === 200) {
        alert('提交充值申请成功，请等待审核');
        setIsRechargeModalVisible(false);
        // 刷新会员详情数据
        const memberResponse = await _apiMemberInfo({
          userId: currentMember.userId
        });
        if (memberResponse?.data) {
          setCurrentMember(memberResponse.data);
        }
        // 刷新储值记录
        fetchRechargeRecords(currentMember.userId);
      } else {
        alert(response?.msg || '充值失败');
      }
    } catch (error) {
      console.error('充值失败:', error);
      alert('充值失败，请重试');
    }
  };

  // 充值弹窗
  const renderRechargeModal = () => (
    <Modal
      title="储值充值"
      open={isRechargeModalVisible}
      onOk={handleRechargeSubmit}
      onCancel={() => setIsRechargeModalVisible(false)}
      okText="确认充值"
      cancelText="取消"
      width={500}
    >
      <div className={styles.formItem}>
        <span className={styles.label}>充值金额：</span>
        <Input
          value={rechargeForm.rechargeAmount}
          onChange={e => handleRechargeFormChange('rechargeAmount', e.target.value)}
          placeholder="请输入充值金额"
          style={{ width: '100%' }}
          suffix="元"
        />
      </div>
      <div className={styles.formItem}>
        <span className={styles.label}>支付方式：</span>
        <Select
          value={rechargeForm.paymentMethod}
          onChange={value => handleRechargeFormChange('paymentMethod', value)}
          style={{ width: '100%' }}
          placeholder="请选择支付方式"
        >
          {paymentTypes.map(type => (
            <Select.Option key={type.id} value={type.id}>
              {type.id === 1 ? '余额' : type.id === 2 ? '微信' : type.name}
            </Select.Option>
          ))}
        </Select>
      </div>
    </Modal>
  );

  // 处理编辑表单变化
  const handleEditFormChange = (field, value) => {
    setEditForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理编辑按钮点击
  const handleEdit = (record) => {
    setEditForm({
      name: record.realName || record.userName || '',
      phone: record.phone || '',
      gender: record.sex || '男'
    });
    setIsEditModalVisible(true);
  };

  // 处理提交编辑
  const handleEditSubmit = () => {
    // TODO: 处理编辑提交逻辑
    setIsEditModalVisible(false);
  };

  // 编辑会员资料弹窗
  const renderEditModal = () => (
    <Modal
      title="编辑会员资料"
      open={isEditModalVisible}
      onOk={handleEditSubmit}
      onCancel={() => setIsEditModalVisible(false)}
      okText="提交"
      cancelText="取消"
      width={600}
    >
      <div className={styles.formItem}>
        <div style={{ display: 'flex', marginBottom: '20px' }}>
          <div style={{ flex: 1 }}>
            <span className={styles.label}>会员姓名：</span>
            <Input
              value={editForm.name}
              onChange={e => handleEditFormChange('name', e.target.value)}
              style={{ width: '200px' }}
            />
          </div>
        </div>
        <div style={{ display: 'flex', marginBottom: '20px' }}>
          <div style={{ flex: 1 }}>
            <span className={styles.label}>会员手机：</span>
            <Input
              value={editForm.phone}
              onChange={e => handleEditFormChange('phone', e.target.value)}
              style={{ width: '200px' }}
            />
          </div>
        </div>
      </div>
      <div className={styles.formItem}>
        <span className={styles.label}>会员性别：</span>
        <Radio.Group
          value={editForm.gender}
          onChange={e => handleEditFormChange('gender', e.target.value)}
        >
          <Radio value="男">男</Radio>
          <Radio value="女">女</Radio>
        </Radio.Group>
      </div>
    </Modal>
  );

  // 会员详情页面
  const renderMemberDetail = () => {
    if (!currentMember) return null;
    
    return (
      <div className={styles.container}>
        <div className={styles.header}>
          <div className={styles.breadcrumbContainer}>
            <div className={styles.breadcrumb}>
              当前位置: 会员管理 {'>'} 会员查询 {'>'} 会员详情
            </div>
            <Button 
              onClick={() => setShowDetail(false)}
              className={styles.backButton}
            >
              返回会员列表
            </Button>
          </div>
        </div>

        <div className={styles.detailSection}>
          <div className={styles.basicInfo}>
            <h3>基础资料</h3>
            <div className={styles.memberBasic}>
              <div className={styles.avatarSection}>
                <img src={currentMember.avatar} alt="avatar" className={styles.detailAvatar} />
                <button className={styles.editButton} onClick={() => handleEdit(currentMember)}>
                  编辑资料
                </button>
              </div>
              <div className={styles.infoGrid}>
                <div className={styles.infoItem}>
                  <span>会员姓名：</span>
                  <span>{currentMember.realName}</span>
                </div>
                <div className={styles.infoItem}>
                  <span>会员手机：</span>
                  <span>{currentMember.phone}</span>
                </div>
                <div className={styles.infoItem}>
                  <span>用户ID：</span>
                  <span>{currentMember.id}</span>
                </div>
                <div className={styles.infoItem}>
                  <span>会员性别：</span>
                  <span>{currentMember.sex}</span>
                </div>
                <div className={styles.infoItem}>
                  <span>成为会员时间：</span>
                  <span>{currentMember.regTime}</span>
                </div>
                <div className={styles.infoItem}>
                  <span>最近登录时间：</span>
                  <span>{currentMember.lastTime}</span>
                </div>
              </div>
            </div>
          </div>

          <div className={styles.assetsInfo}>
            <h3>会员资产</h3>
            <div className={styles.assetsGrid} style={{ 
              display: 'grid',
              gridTemplateColumns: '1fr 1fr',
              gap: '24px',
              marginTop: '16px',
              maxWidth: '8000px' 
            }}>
              <div className={styles.assetItem}>
                <div>累计积分</div>
                <div>{currentMember.point}</div>
              </div>
              <div className={styles.assetItem}>
                <div>储值卡余额（元）</div>
                <div>{currentMember.amount}</div>
                <a onClick={() => handleRecharge(currentMember)}>充值</a>
              </div>
            </div>
          </div>
        </div>

        <div className={styles.recordTabs}>
          <div className={styles.tabHeader}>
            <span 
              className={activeTab === 'storage' ? styles.activeTab : ''}
              onClick={() => setActiveTab('storage')}
            >
              储值记录
            </span>
            <span 
              className={activeTab === 'points' ? styles.activeTab : ''}
              onClick={() => setActiveTab('points')}
            >
              积分记录
            </span>
            <span 
              className={activeTab === 'coupons' ? styles.activeTab : ''}
              onClick={() => setActiveTab('coupons')}
            >
              优惠券
            </span>
            <span 
              className={activeTab === 'orders' ? styles.activeTab : ''}
              onClick={() => setActiveTab('orders')}
            >
              订单记录
            </span>
          </div>
          {renderTabContent()}
        </div>
      </div>
    );
  };

  // 渲染当前标签页对应的表格
  const renderTabContent = () => {
    switch (activeTab) {
      case 'storage':
        return (
          <Table 
            columns={storageColumns} 
            dataSource={rechargeRecords}
            loading={rechargeLoading}
            locale={{
              emptyText: <EmptyState />
            }}
            pagination={{
              total: rechargeRecords.length,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
            }}
          />
        );
      case 'points':
        return (
          <Table 
            columns={pointsColumns} 
            dataSource={integralRecords}
            loading={integralLoading}
            locale={{
              emptyText: <EmptyState />
            }}
            pagination={{
              total: integralRecords.length,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
            }}
          />
        );
      case 'coupons':
        console.log('Current coupon records:', couponRecords); // 添加调试日志
        return (
          <Table 
            columns={couponColumns} 
            dataSource={couponRecords}
            loading={couponLoading}
            locale={{
              emptyText: <EmptyState />
            }}
            pagination={{
              total: couponRecords?.length || 0,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
            }}
            rowKey={record => record.id || Math.random().toString()}
          />
        );
      case 'orders':
        return (
          <Table 
            columns={orderColumns} 
            dataSource={orderData}
            loading={orderLoading}
            locale={{
              emptyText: <EmptyState />
            }}
            pagination={{
              total: orderData?.length || 0,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
            }}
          />
        );
      case 'integral':
        return (
          <Table 
            columns={integralColumns} 
            dataSource={integralRecords}
            loading={integralLoading}
            locale={{
              emptyText: <EmptyState />
            }}
            pagination={{
              total: integralRecords.length,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
            }}
          />
        );
      default:
        return (
          <Table 
            columns={[]}
            dataSource={[]}
            locale={{
              emptyText: <EmptyState />
            }}
          />
        );
    }
  };

  // 修改操作列的处理函数
  const handleMemberDetail = (record) => {
    console.log('Member detail record:', record);
    
    if (!record || !record.id) {
      console.error('Invalid record or missing id');
      return;
    }

    setCurrentMember(record);
    setShowDetail(true);
    fetchRechargeRecords(record.id);
    fetchIntegralRecords(record.id);
    fetchCouponRecords(record.id);
    fetchOrderRecords(record.id);
    
    console.log('Using member id:', record.id);
  };

  // 添加获取会员列表的函数
  const fetchMemberList = async (params = {}) => {
    try {
      setLoading(true);
      const { current = 1, pageSize = 10 } = params;
      const response = await _apiMemberList({
        page: current,
        pageSize,
        storeId: selectedStore,
        orderCount: selectedOrders,
      });

      
      
      if (response?.data) {
        // 确保 response.data 是数组
        const list = Array.isArray(response.data) ? response.data : [];
       
        
        setMemberList(list);
        setPagination({
          current,
          pageSize,
          total: list.length,
        });
      }
    } catch (error) {
      console.error('获取会员列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 添加页面加载时的副作用
  useEffect(() => {
    fetchMemberList();
  }, []);

  // 添加表格变化处理函数
  const handleTableChange = (pagination, filters, sorter) => {
    fetchMemberList({
      current: pagination.current,
      pageSize: pagination.pageSize,
      // 如果需要，也可以添加排序参数
      // sortField: sorter.field,
      // sortOrder: sorter.order,
    });
  };

  // 修改查询按钮点击处理函数
  const handleSearch = () => {
    fetchMemberList({
      current: 1, // 重置到第一页
      pageSize: pagination.pageSize
    });
  };

  // 修改获取支付方式的函数，添加参数
  const fetchPaymentTypes = async () => {
    try {
      const response = await _apiPayType({
        top: 100
      });
      if (response?.data) {
        setPaymentTypes(response.data);
      }
    } catch (error) {
      console.error('获取支付方式失败:', error);
    }
  };

  // 在组件加载时立即调用
  useEffect(() => {
    fetchPaymentTypes();
  }, []);

  // 添加获取储值记录的函数
  const fetchRechargeRecords = async (userId) => {
    try {
      setRechargeLoading(true);
      const response = await _apiRechargeList({
        userId,
        page: 1,
        pageSize: 10
      });
      
      if (response?.data) {
        setRechargeRecords(response.data);
      }
    } catch (error) {
      console.error('获取储值记录失败:', error);
    } finally {
      setRechargeLoading(false);
    }
  };

  // 修改获取积分记录的函数
  const fetchIntegralRecords = async (userId) => {
    try {
      setIntegralLoading(true);
      const response = await _apiIntegralList({
        userId,
        page: 1,
        pageSize: 10
      });
      
      if (response?.data) {
        // 确保数据是数组格式
        const records = Array.isArray(response.data) ? response.data : [response.data];
        // 处理数据，添加 key 属性
        const formattedRecords = records.map(record => ({
          ...record,
          key: record.id || Math.random().toString(), // 确保每行都有唯一的 key
        }));
        setIntegralRecords(formattedRecords);
      }
    } catch (error) {
      console.error('获取积分记录失败:', error);
    } finally {
      setIntegralLoading(false);
    }
  };

  // 添加获取优惠券记录的函数
  const fetchCouponRecords = async (id) => {
    try {
      setCouponLoading(true);
      const response = await _apiCouponList({id:id});
      
      if (response?.data) {
        const records = Array.isArray(response.data) ? response.data : [response.data];
        const formattedRecords = records.map(record => ({
          ...record,
          key: record.id || Math.random().toString(),
        }));
        setCouponRecords(formattedRecords);
      }
    } catch (error) {
      console.error('获取优惠券记录失败:', error);
    } finally {
      setCouponLoading(false);
    }
  };

  // 修改获取订单记录的函数
  const fetchOrderRecords = async (userId) => {
    try {
      setOrderLoading(true);
      // 修改：传入对象参数，包含 userId
      const response = await _apiOrderList({ userId: userId });
      
      if (response?.data) {
        const records = Array.isArray(response.data) ? response.data : [response.data];
        const formattedRecords = records.map(record => ({
          ...record,
          key: record.id || Math.random().toString(),
        }));
        setOrderData(formattedRecords);
      }
    } catch (error) {
      console.error('获取订单记录失败:', error);
    } finally {
      setOrderLoading(false);
    }
  };

  // 渲染主体内容
  return (
    <>
      {showDetail ? renderMemberDetail() : (
        <div className={styles.container}>
          <div className={styles.header}>
            <div className={styles.breadcrumb}>
              当前位置: 会员管理 {'>'} 会员查询
            </div>
            
            <div className={styles.filterSection}>
              <div className={styles.filterItem}>
                <span>所属门店：</span>
                <Select 
                  value={selectedStore} 
                  onChange={setSelectedStore}
                  style={{ width: 200 }}
                >
                  <Option value="1">1</Option>
                </Select>
              </div>

              <div className={styles.filterItem}>
                <span>下单次数：</span>
                <Select
                  value={selectedOrders}
                  onChange={setSelectedOrders}
                  style={{ width: 200 }}
                >
                  <Option value="1">1</Option>
                </Select>
              </div>

              <div className={styles.filterItem}>
                <span>成为会员日期：</span>
                <RangePicker />
                <Button type="primary" className={styles.searchButton} onClick={handleSearch}>
                  查询
                </Button>
              </div>
            </div>
          </div>

          <Table 
            columns={columns} 
            dataSource={memberList}
            pagination={pagination}
            loading={loading}
            onChange={handleTableChange}
          />
        </div>
      )}
      {renderPointsModal()}
      {renderRechargeModal()}
      {renderEditModal()}
    </>
  );
};

export default MemberManagement;
